//============================================================================
// Name        : client.cpp
// Author      : Jessica Brazelton
// Course	   : CS 6210 Advanced Operating Systems
// Description :
//============================================================================

//================== HEADER FILES ==================
#include <iostream>						// for I/O
#include <assert.h>
#include <xmlrpc-c/girerr.hpp>
#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/client_simple.hpp>

using namespace xmlrpc_c;
using namespace std;

// =================== Symbolic Constants ========================
const int NUM_SERVICES = 3;


int main(int size, char* param[]) {
	int num_requests;
	double responseTime, avg_response;

	if (size - 1 != 1) {
		cout << "You must specify the number of requests" << endl;
		return 1;
	}

	num_requests = atoi(param[1]);

	try {
		string const methodName("flipCoin");

//		for (int k = 0; k < num_requests; k++) {
//			cout << "R" << k << ": ";

			clientXmlTransport_curl myTransport;
			client_xml myClient(&myTransport);
			paramList sampleAddParms;

			string serverUrl1("http://localhost:8080/RPC2");
			string serverUrl2("http://localhost:8081/RPC2");
			string serverUrl3("http://localhost:8082/RPC2");

			carriageParm_curl0 myCarriageParm1(serverUrl1);
			carriageParm_curl0 myCarriageParm2(serverUrl2);
			carriageParm_curl0 myCarriageParm3(serverUrl3);

			rpcPtr rpc1P(methodName, sampleAddParms);
			rpcPtr rpc2P(methodName, sampleAddParms);
			rpcPtr rpc3P(methodName, sampleAddParms);

			rpc1P->start(&myClient, &myCarriageParm1);
			rpc2P->start(&myClient, &myCarriageParm2);
			rpc3P->start(&myClient, &myCarriageParm3);

			myClient.finishAsync(timeout());  // infinite timeout
			assert(rpc1P->isFinished());
			assert(rpc2P->isFinished());
			assert(rpc3P->isFinished());

			int const result1(value_int(rpc1P->getResult()));
			int const result2(value_int(rpc2P->getResult()));
			int const result3(value_int(rpc3P->getResult()));
	        cout << result1 << "|" << result2 << "|" << result3 << endl;


//			for (int i = 0; i < NUM_SERVICES; i++) {
//				string serverUrl(url[i]);
//				string const methodName("flipCoin");
//
//				clientSimple myClient;
//				value result;
//
//				usleep(50000);
//
//				clock_t startTime = clock();
//				myClient.call(serverUrl, methodName, "ii", &result);
//				int const side = value_int(result);
//				// Assume the method returned an integer; throws error if not
//				clock_t endTime = clock();
//
//				responseTime += ((double)(endTime - startTime) / CLOCKS_PER_SEC) * 1000;
//				// convert time to milliseconds
//
//				cout << side << "|";
//			}
//			cout << endl;
//		}

//		avg_response = responseTime / num_requests;
//		cout << "Average Response Time: " << avg_response << endl;

	} catch (exception const& e) {
		cerr << "Client threw error: " << e.what() << endl;
	} catch (...) {
		cerr << "Client threw unexpected error." << endl;
	}

	return 0;

} // end main
